package org.arnetminer.personalized.service;

import java.util.ArrayList;
import java.util.List;

import org.arnetminer.personalized.dao.MessageDAO;
import org.arnetminer.personalized.util.Page;
import org.arnetminer.personalized.vo.Message;
import org.arnetminer.personalized.vo.User;

public class MessageServiceImpl implements MessageService {
	
	MessageDAO messageDAO;

	public MessageDAO getMessageDAO() {
		return messageDAO;
	}

	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}
	
	public boolean save(Message message) {
		
		try {
			messageDAO.save(message);

		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	
	public List getUserInMessage(User user, Page page, int isDraft) {
		List<String> properties = new ArrayList();
		List values = new ArrayList();
		properties.add("receiver");
		values.add(user);
		
		properties.add("isDraft");
		values.add(isDraft);

		properties.add("inOrout");
		values.add(1);
		
		List messages = messageDAO
				.findByProperties(properties, values, page.getPageStartRow(), page.getPageRecorders());
		return messages;
	}
	
	public int getInCountByUser(User user, int isDraft) {
		return messageDAO.findInCountByUser(user, isDraft);
	}
	
	public List getUserOutMessage(User user, Page page, int isDraft) {
		List<String> properties = new ArrayList();
		List values = new ArrayList();
		properties.add("sender");
		values.add(user);
		
		properties.add("isDraft");
		values.add(isDraft);
		
		properties.add("inOrout");
		values.add(0);

		List messages = messageDAO
				.findByProperties(properties, values, page.getPageStartRow(), page.getPageRecorders());
		return messages;
	}
	
	public int getOutCountByUser(User user, int isDraft) {
		
		return messageDAO.findOutCountByUser(user, isDraft);
	}
	
	public Message getMessage(long id) {
		return messageDAO.findById(id);
	}
	
	public boolean delete(long id, User user) {
		Message message = messageDAO.findById(id);
		if (message != null) {
			if ((message.getSender().getId() == user.getId() && message.getInOrout() == 0) || (message.getReceiver().getId() == user.getId() && message.getInOrout() == 1)) {
				messageDAO.delete(message);
				return true;
			}
		}
		return false;
	}
}
